<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>

		<script type="text/javascript">
			// 创建一个8字节的ArrayBuffer
			var b = new ArrayBuffer(8);

			// 创建一个指向b的Int32视图，开始于字节0，直到缓冲区的末尾
			var v1 = new Int32Array(b);
			//			console.log(v1.length)
			// 创建一个指向b的Uint8视图，开始于字节2，直到缓冲区的末尾
			var v2 = new Uint8Array(b, 2);
			//			console.log(v2.length)
			// 创建一个指向b的Int16视图，开始于字节2，长度为2
			var v3 = new Int16Array(b, 2, 2);
			//			console.log(v3.length)
			v3[0] = 1
			v2[0] = 25
			v1[0] = 25
			//			console.log(v1[0])
			//			console.log(v2[0])
			//			console.log(v3[0])

			// ArrayBuffer转为字符串，参数为ArrayBuffer对象
			function ab2str(buf) {
				return String.fromCharCode.apply(null, new Uint16Array(buf));
			}

			// 字符串转为ArrayBuffer对象，参数为字符串
			function str2ab(str) {
				var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
				var bufView = new Uint16Array(buf);
				for(var i = 0, strLen = str.length; i < strLen; i++) {
					bufView[i] = str.charCodeAt(i);
					//					console.log(str.charCodeAt(i))
				}
				return buf;
			}
			str2ab('str')
			//			console.log(ab2str(b))

			//生成一个32位长度的乱码
			var len = 32;
			var ab = new ArrayBuffer(len);
			var un8 = new Uint16Array(ab);
			for(var i = 0; i < un8.length; i++) {
				//				console.log(Math.floor(Math.random()*155 + 100))
				un8[i] = Math.floor(Math.random() * 32 + 41)
			}
			var strin = String.fromCharCode.apply(null, new Uint16Array(ab));
			console.log(strin);
		</script>
	</body>
</html>